import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./techportal.db")

# SQLite 需要 check_same_thread
if DATABASE_URL.startswith("sqlite"):
    engine = create_engine(
        DATABASE_URL,
        echo=False,
        future=True,
        connect_args={"check_same_thread": False}
    )
else:
    engine = create_engine(
        DATABASE_URL,
        echo=False,
        future=True,
        pool_pre_ping=True
    )

SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
Base = declarative_base()


def init_db():
    """在应用启动时初始化所有模型对应的表"""
    from app.models.quant_order import QuantOrder  # noqa: F401
    from app.models.strategy_token import StrategyToken  # noqa: F401
    from app.models.stock_dict import StockDict  # noqa: F401
    Base.metadata.create_all(bind=engine)